import { useQuery } from "@tanstack/react-query";
import { Badge, Modal, Table, Tabs, Tree } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react"

import { listAppTree } from '@/api/system/dept'
import { getPermissionData } from '@/api/system/user'
import DisplayLabel from "@/components/displayLabel";


const UserPermissionModal = forwardRef((_, ref) => {
  const [userId, setUserId] = useState()
  const [isModalOpen, setIsModalOpen] = useState()
  const [activeKey, setActiveKey] = useState('1')
  const { data: treeOptions } = useQuery({
    queryKey: ['userSelectTree'],
    queryFn: () => {
      return listAppTree().then((response) => {
        // setExpandedKeys(expandTree(response.data, 3))
        return response.data
      })
    },
    staleTime: 0,
  })

  const { data: permissionInfo } = useQuery({
    queryKey: ['getPermissionData', userId],
    queryFn: () => {
      return getPermissionData(userId).then((response) => {
        // setExpandedKeys(expandTree(response.data, 3))
        return response.data
      })
    },
    staleTime: 0,
    enabled: !!userId
  })

  useImperativeHandle(ref, () => ({
    showModal: (row) => {
      setUserId(row.id)
      setActiveKey('1')
      setIsModalOpen(true)
    },
  }));

  const handleOk = () => {
    setIsModalOpen(false)
  }
  return <Modal
    width={520}
    title="应用绑定"
    open={isModalOpen}
    onOk={handleOk}
    onCancel={() => setIsModalOpen(false)}>
    <Tabs activeKey={activeKey} items={[
      { label: `功能`, key: '1', children: <FunctionalTree treeOptions={treeOptions} permissionInfo={permissionInfo} /> },
      {
        label: `角色`, key: '2', children: <Table style={{ height: '400px' }}
          pagination={false} rowKey={(record) => record.id} columns={[
            {
              title: '角色名称',
              dataIndex: 'roleName',
              ellipsis: true
            },
            {
              title: '角色编码',
              dataIndex: 'roleKey',
              ellipsis: true
            },
            {
              title: '角色状态',
              dataIndex: 'status',
              align: 'center',
              render: (text) => (<Badge status={text == '0' ? 'processing' : 'error'} text={<DisplayLabel value={text} type="sys_normal_disable" />} />)
            },
            {
              title: '备注',
              dataIndex: 'remark',
              align: 'center'
            }
          ]} dataSource={permissionInfo?.role} />
      }
    ]} onChange={setActiveKey} />
  </Modal>
})

const FunctionalTree = ({ treeOptions, permissionInfo }) => {
  const [checkedKeys, setCheckedKeys] = useState([])
  const [expandedKeys, setExpandedKeys] = useState([])

  useEffect(() => {
    if (permissionInfo) {
      setCheckedKeys([...permissionInfo.appMenu])
      setExpandedKeys([...permissionInfo.appMenu])
    }
  }, [permissionInfo])
  const onCheck = (val, data) => {
    setCheckedKeys(val)
  }
  return <div style={{ height: '400px', overflow: 'auto' }}>
    <Tree
      checkable
      disabled
      treeData={treeOptions}
      expandedKeys={expandedKeys}
      onExpand={(expandedKeys) => {
        setExpandedKeys(expandedKeys);
      }}
      onCheck={onCheck}
      checkedKeys={checkedKeys}
      autoExpandParent={true}
    />
  </div>
}

export default UserPermissionModal